package Concurrent;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Description：
 * Author: zhangc
 * Date：2017/9/23 16:37
 */
public class MySemaphore {

    private static Queue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
    private static Semaphore semaphore = new Semaphore(5);

    static {
        for (int i = 0; i < 5; i++) {
            queue.add(i);
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 50; i++) {
            executorService.execute(new Th());
        }
        executorService.shutdown();
    }

    static class Th implements Runnable {

        @Override
        public void run() {
            Integer remove = 0;
            try {
                semaphore.acquire();
                remove = queue.remove();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println(remove);
                queue.add(remove * 2);
                semaphore.release();
            }
        }
    }

}
